package com.jpxx.jpscp.admin.aspect;

import com.jpxx.jpscp.admin.log.entity.Log;
import com.jpxx.jpscp.admin.log.service.LogService;
import com.jpxx.jpscp.admin.system.entity.User;
import com.jpxx.jpscp.core.common.annotation.SysLog;
import com.jpxx.jpscp.core.util.WebUtils;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @Description: 日志切人点
 * @author: Zhaopengfei
 * @copyright: 金鹏信息技术有限公司
 * @CreatedDate: 2018年03月22日 15:05
 * @Copyright: All rights Reserved，Designed By Jpsycn
 */
@Aspect
@Component
public class SystemLogAspect {
    //本地异常日志记录对象
    private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);
    //注入Service用于把日志保存数据库
    @Autowired
    private LogService logService;

    //Controller层切点
    @Pointcut("@annotation(com.jpxx.jpscp.core.common.annotation.SysLog)")
    public  void controllerAspect() {
    }

    /**
     * 前置通知 用于拦截Controller层记录用户的操作
     *
     * @param joinPoint 切点
     */
    @Before("controllerAspect()")
    public  void doBefore(JoinPoint joinPoint) {

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        //读取session中的用户
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        //请求的IP
        //String ip = request.getRemoteAddr();
        String ip= WebUtils.getRemoteAddr(request);
        String method = joinPoint.getSignature().getDeclaringTypeName() +
                "." + joinPoint.getSignature().getName();
        String params = "";
        if (joinPoint.getArgs() !=  null && joinPoint.getArgs().length > 0) {
            for ( int i = 0; i < joinPoint.getArgs().length; i++) {
                params+=joinPoint.getArgs()[i]+";";
            }
        }
        try {
            //*========控制台输出=========*//
            //System.out.println("=====前置通知开始=====");
            String operation=getControllerMethodDescription(joinPoint);
            String username=user.getUserName();
            //System.out.println("请求参数:" + params);
            Log log=new Log();
            log.setCreateDate(new Date());
            log.setRemoteAddr(ip);
            log.setMethod(operation);
            log.setParams(params);
            log.setUserAgent(username);
            log.setMethod(method);
            //*========保存数据库日志=========*//
            //System.out.println(log);
            logService.save(log);
            //保存数据库
        }  catch (Exception e) {
            //记录本地异常日志
            logger.error("==前置通知异常==");
            logger.error("异常信息:{}", e.getMessage());
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param joinPoint 切点
     * @return 方法描述
     * @throws Exception
     */
    public  static String getControllerMethodDescription(JoinPoint joinPoint)  throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description = method.getAnnotation(SysLog.class).value();
                    break;
                }
            }
        }
        return description;
    }

}
